<?php

namespace App\Http\Controllers\Admin;

use App\Http\Models\Category;

class CategoryController extends CommonController
{
    public function index(){
        $data = Category::tree();
        return view('admin.category.index', ['data' => $data]);
    }
    
    public function changeOrder(){
        $input = \Input::all();
        $cate = Category::find($input['cate_id']);
        $cate->cate_order = $input['cate_order'];
        $r = $cate->update();
        
        $result = [];
        
        $result['status'] = ($r) ? 0 : 1;
        $result['msg'] = ($r) ? '排序更新成功！' : '排序更新失败！';
        
        return $result;
    }
    
    public function create(){
        $data = Category::where('cate_parentid', 0)->get();
        return view('admin.category.add', ['data' => $data]);
    }    
    
    public function store(){
        $input = \Input::except('_token');
        if ($input) {
            $rlues = [
                'cate_name' => 'required',
            ];

            $messages = [
                'cate_name.required' => '分类名称不能为空！',
            ];
            
            $validator = \Validator::make($input, $rlues, $messages);
            if ($validator->passes()) {
                $r = Category::create($input);
                if($r)
                    return back()->with('errors', '分类创建成功！');
                else 
                    return back()->with ('errors', '创建失败，请稍后再试！');
            } else
                return back()->withErrors($validator);
        }
    }

    public function show(){
        
    }

    public function edit($cate_id){
        $field = Category::find($cate_id);
        $data = Category::where('cate_parentid', 0)->get();
        return view('admin.category.edit', ['field' => $field, 'data' => $data]);
    } 
    
    public function update($cate_id){
        $input = \Input::except('_token', '_method');
        $r = Category::where('cate_id', $cate_id)->update($input);
        
        return back()->with('errors', ($r) ? '分类更新成功':'分类更新失败，请稍后再试！');
    }

    public function destroy($cate_id){
        $r = Category::where('cate_id', $cate_id)->delete();
        Category::where('cate_parentid', $cate_id)->update(['cate_parentid' => 0]);
        
        $data = [];
      
        $data['status'] = ($r) ? 0 : 1;
        $data['msg'] = ($r) ? '删除成功':'删除失败请稍后再试！';
       
        return $data;  
    }
}
